package com.weight.common.util;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;


/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 * @author ThinkGem
 * @version 2013-3-15
 */
public class DateFormUtils{
	 
	/**
	 * 	Date时间转String字符串
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getDateToString(Date date, String pattern ) {
		String formatDate = null;
		if (date != null&&StringUtils.isNotBlank(pattern)) {
			formatDate = DateFormatUtils.format(date, pattern);
		}
		return formatDate;
	}
	/**
	 * String字符串转Date时间
	 * @param dateStr
	 * @param pattern
	 * @return
	 */
	public static Date getStringToDate(String dateStr,String pattern ) {
		if (StringUtils.isNotBlank(dateStr)&&StringUtils.isNotBlank(pattern)) {
			try {
				return DateUtils.parseDate(dateStr, pattern);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	} 
	public static Date getStringToDate(String dateStr) {
		if (StringUtils.isNotBlank(dateStr)) {
			try {
				return DateUtils.parseDate(dateStr, "yyyy-MM-dd");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	} 
	/**
	 * 计算时间差  
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public static Integer daysBetween(Date date1, Date date2) {
	   if(date1!=null&&date2!=null) {
	        Calendar cal = Calendar.getInstance();
	        cal.setTime(date1);
	        long time1 = cal.getTimeInMillis();
	        cal.setTime(date2);
	        long time2 = cal.getTimeInMillis();
	        long between_days=0;
	        if(time2>time1) {
	        	 between_days= (time2 - time1) / (1000 * 3600 * 24);
	        }else {
	        	 between_days= (time1 - time2) / (1000 * 3600 * 24);
	        }
	        return Integer.parseInt(String.valueOf(between_days));
	   }
	   return null;
    }
	public static Integer daysBetween(String date1, String date2){
	   if(StringUtils.isNotBlank(date1)&&StringUtils.isNotBlank(date2)) {
	       return daysBetween(getStringToDate(date1),getStringToDate(date2));
	   }
	   return null;
    }
}
